<?php
class Index extends Action {
	/*
	 * (non-PHPdoc) @see Action::execute()
	 */
	public function execute($params) {
		global $__url, $__cpage;
		$url = Response::$url;
		$preview = rqset ( 'preview' );
		$pid = false;
		if ($preview) { // 预览
			$I = check_login ( ADMIN_LOGIN_PAGE );
			$content = false;
			$pid = irqst ( 'pid' );
		} else {
			$cache_id = md5 ( $_SERVER ['HTTP_HOST'] . $url . $_SERVER ['QUERY_STRING'] );
			$content = cache_get ( $cache_id, 'page' );
		}
		if (empty ( $content )) { //缓存未命中
			$params = array ();
			parse_str ( $_SERVER ['QUERY_STRING'], $params );
			unset ( $params ['__url'] );
			$data ['params'] = $params;
			$data ['current_time'] = time();
			$copt = new CoreOptionModel ();			
			if (preg_match ( '/sitemap\.xml$/i', $url )) {
				$pageTpl = CoreOptionModel::getOption('sitemap_tpl','system/sitemap.tpl');
				$cachetime = CoreOptionModel::getOption('sitemap_cache',0);
			} else if (preg_match ( '/rss\.xml$/', $url ) && CoreOptionModel::getOption('rss_enabled',false)) {
				$pageTpl = CoreOptionModel::getOption('rss_tpl','system/rss.tpl');
				$cachetime = CoreOptionModel::getOption('rss_cache',0);
			} else {
				$pM = new WebPageModel ();
				$page = $pM->getPageInfo ( $url, $pid, $preview );
				if (! $page) {
					Response::error ( 'Not Found', 404, true );
				}
				$pageTpl = $page ['template_file'];
				$data ['cpno'] = $__cpage;
				$data ['curl'] = $__url;
				$page ['totalPage'] = 1;
				$page = apply_filter ( 'encapsulated_page', $page );
				
				$opts = $copt->retrieve ( 'option_name,option_value' );
				$data ['_OPT'] = $opts ? $opts->toArray ( 'option_name', 'option_value' ) : array ();
				
				$url = explode ( '.', $__url );
				$ext = '';
				
				if(count($url)> 1){
					$ext = '.'.array_pop ( $url );
				}
				
				$url = implode ( '.', $url ) . '_';
				$data ['page_paging'] = array ('url' => $url, 'cur' => $__cpage, 'total' => $page ['totalPage'], 'per' => 1, 'ext' => $ext );
								
				$data ['page'] = $page;
				$cachetime = intval ( $page ['cachetime'] );
			}
			$view = new TemplateView ( $data, $pageTpl );
			$content = $view->render ( $this, null );
						
			if (! $preview && $cachetime > 0) {
				cache_add ( $cache_id, $content, $cachetime, 'page' );
			}
		}
		if (! empty ( $content )) { //此外为大显神通之笔
			$pattern = '#(<!--placeholder:([a-z][\d\w_]*)-->)(?:(?!<!--?/placeholder*-->)[\s\S])*(<!--/placeholder:\2-->)#m';
			if (preg_match_all ( $pattern, $content, $matches, PREG_SET_ORDER )) {
				foreach ( $matches as $key => $val ) {
					$search = $val [0];
					$keyword = $val [2];
					$replace = apply_filter ( 'replace_placeholder_' . $keyword, false );
					if ($replace) {
						$content = str_replace ( $search, $replace, $content );
					} else {
						$content = str_replace ( array ($val [1], $val [3] ), '', $content );
					}
				}
			}
		}
		echo $content;
		Response::close ();
	}
}